from django.contrib.auth.models import UserManager, GroupManager, Permission
from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser, PermissionsMixin
)
from django.utils.translation import gettext_lazy as _

from thinghoo_library.models import TimeModel
# Create your models here.


class Team(TimeModel):
    name = models.CharField(max_length=255)


class CdUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(
        _('UserName'),
        max_length=255,
        unique=True,
    )
    email = models.EmailField(_('email address'), blank=True)

    role = models.ManyToManyField(to="Role", blank=True, verbose_name="Roles", help_text="关联角色")

    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )

    is_admin = models.BooleanField(default=False)
    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    # 设置返回值
    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    # 新增部分权限
    class Meta(AbstractBaseUser.Meta):
        verbose_name = "User"
        # 自定义权限
        permissions = (
            # 草稿 可写前端 hash
            ('front_hash', 'Can write draft front hash'),
            # 草稿 可写后端 hash
            ('back_hash', 'Can write draft back hash')
        )


class Role(models.Model):
    USERTYPE_CHOICE = (
        (0, "普通用户"),
        (1, "研发经理"),
        (2, "项目经理"),
        (3, "前端研发工程师"),
        (4, "后端研发工程师"),
        (5, "实施主管"),
        (6, "运维人员"),
        (7, "产品经理"),
        (8, "测试工程师"),
    )
    usertype = models.IntegerField(choices=USERTYPE_CHOICE, verbose_name="角色名称", help_text="角色名称")
    remark = models.TextField(verbose_name="备注", help_text="备注", null=True, blank=True)
    permission = models.ManyToManyField(
        Permission, verbose_name="permissions", blank=True, help_text="关联用户权限"
    )
    objects = GroupManager()

    class Meta:
        verbose_name = "角色表"
